#!/usr/bin/env python3
# encoding=utf-8

import poplib
from commom_api import get_sec_info
from email_process import is_mail_filter_info, parser_context_info
import logging
logger = logging.getLogger(__name__)

def get_mail_pop_handle(): 
    sinfo = get_sec_info()
    # 创建连接
    if sinfo['ssl'] == 1:
        conn = poplib.POP3_SSL(sinfo['mail'], sinfo['port'])
    else:
        conn = poplib.POP3(sinfo['mail'], sinfo['port'])
    # 登录服务器
    conn.user(sinfo['user'])
    conn.pass_(sinfo['passwd']) # 注意输入的是邮箱授权码而不是真实QQ密码
    return conn

def get_pop_mail_info():
    conn = get_mail_pop_handle()
    # 获取邮件列表
    response, maillist, r = conn.list()
    logger.info("mail rsp:[%s] len:%d" % (response, len(maillist)))
    
    emailinfo = []
    # 遍历邮件
    for i in range(len(maillist)):
        response, lines, octets = conn.top(i+1, 0)
        data = b'\r\n'.join(lines)
        ret = is_mail_filter_info(data)
        if ret <= 0:
            continue
        response, lines, octets = conn.retr(i+1)
        data = b'\r\n'.join(lines)
        oneinfo = parser_context_info(data)
        if len(oneinfo) == 0:
            continue
        for one in oneinfo:
            if one == None:
                continue
            emailinfo.append(one)

    # 退出服务器
    conn.quit()
    return emailinfo

def get_data_by_pop(): 
    emailinfo = get_pop_mail_info()
    return emailinfo

if __name__=="__main__":
    get_data_by_pop()